
import 'package:flutter/cupertino.dart';
import 'package:flutter_deer/login/iview/login_sms_iview.dart';
import 'package:flutter_deer/mvp/base_page_presenter.dart';
import 'package:flutter_deer/net/base_entity.dart';
import 'package:flutter_deer/net/net.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/shop/models/user_entity.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:sp_util/sp_util.dart';

class LoginSmsPagePresenter extends BasePagePresenter<LoginSmsIMvpView> {

  @override
  void initState() {
  }

  Future<dynamic> sendLoginSmsCode(String mobile) async {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      requestNetwork<OperatorBaseEntity>(Method.get,
          url: HttpApi.sendLoginSmsCode.replaceAll("{mobile}", mobile),
          onSuccess: (data) {
            view.setLoginSmsCode(data);
          },
          onError: (code, msg) {
            dispose();
          }
      );
    });
  }

  Future<dynamic> loginBySmsCode(String? mobile,String? code) async {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final Map<String, dynamic> params = <String, dynamic>{};
      params['grant_type'] = 'mobile';
      params['mobile'] = 'SMS@${mobile}';
      params['code'] = code;
      requestNetwork<UserTokenEntity>(Method.post,
          url: HttpApi.loginBySmsCode,
          queryParameters: params,
          onSuccess: (data) {
            SpUtil.putString(Constant.tokenType, data!.tokenType.nullSafe);
            SpUtil.putString(Constant.accessToken, data!.accessToken.nullSafe);
            SpUtil.putString(
                Constant.refreshToken, data!.refreshToken.nullSafe);
            SpUtil.putString(Constant.perfect, data!.perfect.nullSafe);
            SpUtil.putString(Constant.phone, mobile.nullSafe);
            view.setUserToken(data);
          },
          onError: (code, msg) {

          }
      );
    });
  }
}
